﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VideoPlay.Services.Models;
using System.Xml.Linq;

namespace VideoPlay.Services.Helpers
{
    public static class YoutubeData
    {
        public static YoutubeSearchResult ParseSearchResultV3(string jsonString)
        {
            return JsonConvert.DeserializeObject<YoutubeSearchResult>(jsonString);
        }

        public static List<List> ParseSearchResultV2(string xml)
        {
            List<List> result = new List<List>();

            try
            {
                XElement xmlData = XElement.Parse(xml);

                XNamespace ns = "http://www.w3.org/2005/Atom";
                XNamespace media = "http://search.yahoo.com/mrss/";
                XNamespace app = "http://purl.org/atom/app#";
                XNamespace openSearch = "http://a9.com/-/spec/opensearchrss/1.0/";
                XNamespace gd = "http://schemas.google.com/g/2005";
                XNamespace yt = "http://gdata.youtube.com/schemas/2007";

                foreach (var item in xmlData.Descendants(ns + "entry"))
                {
                    List video = new List();
                    video.youtubeId = (string)item.Element(media + "group").Element(yt + "videoid").Value;
                    video.title = (string)item.Element(ns + "title").Value;
                    video.image = (string)item.Element(media + "group").Element(media + "thumbnail").Attribute("url").Value;
                    video.url = string.Format("https://www.youtube.com/watch?v={0}", video.youtubeId);

                    double seconds = Convert.ToDouble(item.Element(media + "group").Element(yt + "duration").Attribute("seconds").Value);
                    video.duration = TimeSpan.FromSeconds(seconds);

                    result.Add(video);
                }

            }
            catch (System.Xml.XmlException ex)
            {
                result = null;
            }

            return result;
        }
    }
}
